﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Windows;
using PJ.Business;
using Microsoft.Practices.Composite.Events;

namespace PJ.Presentation
{
    public abstract class BusinessObjectViewModel : BaseViewModel, IBusinessObjectModel
    {
        protected readonly IBusinessObjectService m_Service;

        protected IBusinessObjectService Service
        {
            get 
            {
                if (m_Service == null)
                    throw new ArgumentNullException();
                return m_Service; 
            }
        }

        protected BusinessObjectViewModel(IView view, IEventAggregator aggregator, IBusinessObjectService service)
            : base(view, aggregator)
        {
            m_Service = service;
        }

        /// <summary>
        /// GetValues. Sets the businness object properties using the model property values
        /// </summary>
        /// <param name="businessObject">business object to update</param>
        public virtual IBusinessObject GetValues(IBusinessObject businessObject)
        {
            if (businessObject == null)
                throw new ArgumentNullException();
            if (GlobalID != businessObject.GlobalId)
                if (!string.IsNullOrEmpty(GlobalID) && !string.IsNullOrEmpty(businessObject.GlobalId))
                    throw new ArgumentException();
            return businessObject;
        }
        /// <summary>
        /// SetValues. Sets the model properties using the businessobject property values
        /// </summary>
        /// <param name="businessObject"></param>
        public virtual void SetValues(IBusinessObject businessObject)
        {
            if (businessObject == null)
                throw new ArgumentNullException();
            GlobalID = businessObject.GlobalId;
        }
        
        public string GlobalID
        {
            get 
            {
                return (string)ThreadUnsafeGetValue(GlobalIDProperty); 
            }
            set 
            {
                ThreadUnsafeSetValue(GlobalIDProperty, value); 
            }
        }

        public static readonly DependencyProperty GlobalIDProperty =
            DependencyProperty.Register("GlobalID", typeof(string), typeof(BusinessObjectViewModel), new UIPropertyMetadata(""));


        public virtual void Persist()
        {
            if (m_Service != null)
                Service.Persist(GetValues(Service.CreateNewItem()));
        }

        public override void Dispose()
        {
            Persist();
        }
    }
}
